/* global window */
import modelExtend from 'dva-model-extend'
import * as riskControlService from './services/riskControl'
import * as departmentService from '../department/services/department'
import {pageModel} from 'utils/model'

const {query} = riskControlService

export default modelExtend(pageModel, {
  namespace: 'riskControl',

  state: {
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
    selectedRowKeys: [],
    selectRecord: {},
    disable: false,
    departments: [],
  },

  subscriptions: {
    setup ({dispatch, history}) {
      history.listen((location) => {
        if (location.pathname === '/riskControl') {
          const payload = location.query || {current: 1, size: 10}
          dispatch({
            type: 'query',
            payload,
          })
          dispatch({
            type: 'init',
          })
        }
      })
    },
  },

  effects: {

    * init (_, {call, put}) {
      const response = yield call(departmentService.query)
      const {data} = response
      if (data) {
        yield put({
          type: 'updateState',
          payload: {
            departments: data,
          },
        })
      }
    },

    * query ({payload = {}}, {call, put}) {
      const response = yield call(query, payload)
      const {data} = response
      if (response && data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.records,
            pagination: {
              current: Number(payload.current) || 1,
              pageSize: Number(payload.size) || 10,
              total: data.total,
            },
          },
        })
      }
    },

    * update ({payload}, {call, put}) {
      const data = yield call(riskControlService.update, payload)
      if (data.code === 0) {
        yield put({type: 'hideModal', payload: {
            selectedRowKeys: [],
            currentItem: {},
          }})
      } else {
        throw data
      }
    },

  },

  reducers: {

    showModal (state, {payload}) {
      return {...state, ...payload, modalVisible: true}
    },


    hideModal (state) {
      return {...state, modalVisible: false}
    },



  },
})
